<script lang="ts" setup>
import { reactive, ref, defineExpose } from "vue";
import { createProduct, modifyProduct } from "/@/api/productInfo";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps, FormInstance, FormRules } from "element-plus";
import useUploadUrl from "/@/hooks/useUploadUrl";

const inputWidth = "200px";
const imageUrl = ref("");
const ruleFormRef = ref<FormInstance>();

const rules = reactive<FormRules>({
  name: [{ required: true, message: "请输入", trigger: "chnage" }],
  height: [{ required: true, message: "请输入", trigger: "chnage" }],
  quantity: [{ required: true, message: "请输入", trigger: "chnage" }],
  weight: [{ required: true, message: "请输入", trigger: "chnage" }],
  length: [{ required: true, message: "请输入", trigger: "chnage" }],
  width: [{ required: true, message: "请输入", trigger: "chnage" }]
});

type Props = {
  modelValue: boolean;
  type: string;
  formData: any;
};
const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  type: "",
  formData: () => {
    return {};
  }
});

const emit = defineEmits(["update:modelValue", "submit-success"]);
const inputHandle = val => {
  emit("update:modelValue", val);
};

const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(valid => {
    if (valid) {
      if (props.type === "创建") {
        createProduct(props.formData).then(() => {
          ElMessage({
            type: "success",
            message: "创建成功"
          });
          resetForm(ruleFormRef.value);
          emit("submit-success");
        });
      } else {
        const {
          id,
          name,
          quantity,
          sku,
          weight,
          length,
          width,
          height,
          picture
        } = props.formData;
        const obj = {
          id,
          name,
          quantity,
          sku,
          weight,
          length,
          width,
          height,
          picture
        };
        modifyProduct(obj).then(() => {
          ElMessage({
            type: "success",
            message: "修改成功"
          });
          resetForm(ruleFormRef.value);
          emit("submit-success");
        });
      }
    } else {
      console.log("error submit!");
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  inputHandle(false);
  imageUrl.value = "";
};

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  props.formData.picture = response.data;
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
};

const setImgUrl = val => {
  console.log(val);
  imageUrl.value = val;
};

defineExpose({
  setImgUrl
});
</script>

<template>
  <el-dialog
    :modelValue="modelValue"
    @update:modelValue="inputHandle"
    :title="type + '产品信息'"
    width="55%"
  >
    <span>
      <el-form
        :inline="true"
        :model="formData"
        ref="ruleFormRef"
        :rules="rules"
        label-width="auto"
        label-position="left"
      >
        <el-form-item label="产品名称:" prop="name">
          <el-input v-model="formData.name" :style="{ width: inputWidth }" />
        </el-form-item>
        <el-form-item label="数量:" prop="quantity">
          <el-input-number
            v-model="formData.quantity"
            :step="1"
            :min="0"
            :style="{ width: inputWidth }"
          />
        </el-form-item>
        <el-form-item label="sku:">
          <el-input v-model="formData.sku" :style="{ width: inputWidth }" />
        </el-form-item>
        <el-form-item label="重量:" prop="weight">
          <el-input-number
            v-model="formData.weight"
            :precision="2"
            :min="0"
            :step="0.1"
            :style="{ width: inputWidth }"
          />
        </el-form-item>
        <el-form-item label="箱长:" prop="length">
          <el-input-number
            v-model="formData.length"
            :precision="2"
            :min="0"
            :step="0.1"
            :style="{ width: inputWidth }"
          />
        </el-form-item>
        <el-form-item label="箱宽:" prop="width">
          <el-input-number
            v-model="formData.width"
            :precision="2"
            :min="0"
            :step="0.1"
            :style="{ width: inputWidth }"
          />
        </el-form-item>
        <el-form-item label="箱高:" prop="height">
          <el-input-number
            v-model="formData.height"
            :precision="2"
            :min="0"
            :step="0.1"
            :style="{ width: inputWidth }"
          />
        </el-form-item>
        <el-form-item label="产品图片:" class="picture-form-item">
          <el-upload
            class="avatar-uploader"
            :action="useUploadUrl.uploadUrl"
            :headers="useUploadUrl.headers"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <el-image v-if="imageUrl" :src="imageUrl" fit="cover" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
    </span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="resetForm(ruleFormRef)">取 消</el-button>
        <el-button type="primary" @click="submit(ruleFormRef)">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
:deep(.picture-form-item) {
  vertical-align: top !important;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

:deep(.avatar-uploader .el-upload) {
  width: 150px;
  height: 150px;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

:deep(.avatar-uploader .el-upload:hover) {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
